package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.fastdfsclient.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import com.usian.wemedia.utils.KODOUtils;
import com.usian.wemedia.utils.OSSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import java.util.Date;



@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    // FastDfs
    @Autowired
    private FastDFSClient fastDFSClient;

    // 七牛云
    @Autowired
    private KODOUtils kodoUtils;

    @Value("${wmaterial.baseurl}")
    private String baseurl;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile, Integer state) {
        WmMaterial wmMaterial = null;
        if (multipartFile == null) {
            CatchCustomException.catchs(20001, "文件不能为空!");
        }
        // 1:判断文件Md5值
        // 从线程中获取登录对象
        WmUser wmUser = WmThreadLocalUtils.getUser();
        // 2: 判断用户是否登录
        if (wmUser == null || wmUser.getId() == null) {
            // 提示没有登录的情况
            CatchCustomException.catchs(20002, "没有文件上传权限!");
        }
        // 3: 登陆了：上传 获取fileId
        String imagesUrl = "";
        try {
            if (state == 1) {
                imagesUrl = fastDFSClient.uploadFile(multipartFile);
                // 把图片路径 存入数据库
                wmMaterial = saveUrlByWmMaterial(imagesUrl, wmUser, state);
                // 拼接图片路径
                wmMaterial.setUrl(baseurl + wmMaterial.getUrl());
            } else if (state == 2) {
                // 七牛云
                imagesUrl = kodoUtils.saveImages(multipartFile);
                wmMaterial = saveUrlByWmMaterial(imagesUrl, wmUser, state);
            } else {
                // 阿里云
                OSSClientUtil ossClientUtil = new OSSClientUtil();
                imagesUrl = ossClientUtil.saveImage(multipartFile);
                wmMaterial = saveUrlByWmMaterial(imagesUrl, wmUser, state);
            }

        } catch (IOException e) {
            //上传图片 失败
            CatchCustomException.catchs(20001, "上传图片出现未知错误！");
        }

        // 5: 把上传的图片路径  返回前端
        return ResponseResult.okResult(wmMaterial);
    }
    /**
     * 添加数据
     *
     * @param imageUrl 图片路径
     * @param wmUser   对象
     * @return
     */
    private WmMaterial saveUrlByWmMaterial(String imageUrl, WmUser wmUser, Integer state) {
        // 3.1  创建媒体资源对象
        WmMaterial wmMaterial = new WmMaterial();
        // 3.2   封装各种数据
        wmMaterial.setUrl(imageUrl);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setState(state);
        // 3.3 保存
        this.save(wmMaterial);
        return wmMaterial;
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findPage(WmMaterialDto dto) {
        //  1 判断 dto对象 是否为空 如果为空 提示
        if (dto == null) {
            CatchCustomException.catchs(20001, "参数不能为空!");
        }
        // 2 初始化 分页参数
        dto.checkParam();
        // 3：获取用户ID
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            CatchCustomException.catchs(20003, "没有登陆");
        }
        // 4 根据用户ID 查询相对应的素材
        // 查询条件
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Integer id = wmUser.getId();
        lambdaQueryWrapper.eq(WmMaterial::getUserId, id);
        // 收藏是否为空  不为空 拼接收藏条件
        if (dto.getIsCollection() != null && dto.getIsCollection().shortValue() == 1) {
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //按照时间排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        // 5执行分页结果
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        //6 封装分页结果
        IPage<WmMaterial> ipage = this.page(page, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(ipage.getCurrent(), ipage.getSize(),
                ipage.getTotal());
        responseResult.setData(ipage.getRecords());
        //5 返回
        return responseResult;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        // 判断参数
        if (id == null) {
            CatchCustomException.catchs(20001, "参数不能为空!");
        }
        // 判断用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CatchCustomException.catchs(20005, "没有登陆,不能删除");
        }
        // 查询对应关系
        Integer count =
                wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            CatchCustomException.catchs(20004, "素材已经引用，不能删除!");
        }
        boolean result =
                this.remove(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId, user.getId()).eq(WmMaterial::getId, id));
        if (result){
            //删除对应  oss KODO FastDfs
        }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏图片 和 取消收藏图片
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        // 1 ： 判断参数
        if (id==null){
            CatchCustomException.catchs(20001, "参数不能为空!");
        }
         if (type>1 || type<0){
             CatchCustomException.catchs(20006, "收藏状态有误， 不能操作!");
         }
        // 判断用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CatchCustomException.catchs(20007, "没有登陆,不能操作");
        }
        // 调用修改语句  update set  where
        this.update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,user.getId()));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
